﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft Corp." file="InitializeHostedServiceOperation.cs">
//   All rights reserved. See License.txt in the project root for license information.
// </copyright>
// 
// --------------------------------------------------------------------------------------------------------------------
namespace CloudBlitz.DeploymentManager.DeploymentOperations
{
    using System;
    using System.Linq;

    using AzureManagement.AzureDataContracts;

    using CloudBlitz.DeploymentManager.DeploymentWorkflow;

    public class InitializeHostedServiceOperation : DeploymentOperationBase
    {
        private readonly IAzureServiceClientsFactory azureServiceClientsFactory;

        public InitializeHostedServiceOperation(IAzureServiceClientsFactory azureServiceClientsFactory) : base(5)
        {
            this.azureServiceClientsFactory = azureServiceClientsFactory;
        }

        protected override OperationResult ExecuteOverride(DeploymentContext context)
        {
            var azureServiceManagementClient =
                this.azureServiceClientsFactory.CreateServiceManagementClient(context.AzureCredentials);

            try
            {
                this.RaiseProgressChangedEvent(0, string.Format("Creating hosted service with name \"{0}\"", context.HostedServiceName));

                var hostedServices = azureServiceManagementClient.ListHostedServices().Result;
                if (!hostedServices.Any(x => x.ServiceName.Equals(context.HostedServiceName)))
                {
                    var operationId = azureServiceManagementClient.CreateHostedService(
                                                                        context.HostedServiceName,
                                                                        context.HostedServiceName,
                                                                        context.HostedServiceName,
                                                                        context.Location,
                                                                        null).Result;

                    this.RaiseProgressChangedEvent(50, string.Format("Hosted service \"{0}\" is being created, waiting for the operation to complete", context.HostedServiceName));

                    var operation = azureServiceManagementClient.WaitOperationForCompletion(operationId, TimeSpan.MaxValue);

                    if (operation.Status == OperationStatuses.Failed)
                    {
                        return new OperationResult(DeploymentOperationStatus.Failed, operation.Error.Message);
                    }

                    this.RaiseProgressChangedEvent(100, string.Format("Hosted service \"{0}\" has been created", context.HostedServiceName));
                }
                else
                {
                    this.RaiseProgressChangedEvent(100, string.Format("Hosted service \"{0}\" already exists", context.HostedServiceName));
                }

                return OperationResult.Success;
            }
            catch (Exception e)
            {
                return ExceptionHelper.HandleException(e);
            }
        }

        public void Rollback(DeploymentContext context)
        {
            var azureServiceManagementClient =
                            this.azureServiceClientsFactory.CreateServiceManagementClient(context.AzureCredentials);

            var operationId = azureServiceManagementClient.DeleteHostedService(context.HostedServiceName).Result;

            azureServiceManagementClient.WaitOperationForCompletion(operationId, TimeSpan.MaxValue);
        }
    }
}